package com.shibida.shibidaProject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@SpringBootApplication
public class shibidaProjectApplication {
    public static void main(String[] args) {
        // 启动server.js
        startServer();
        // 添加关闭钩子，在程序结束时关闭server.js
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            // 关闭server.js
            stopServer();
        }));
        //启动Spring Boot应用程序
        SpringApplication.run(shibidaProjectApplication.class, args);
    }
    private static void startServer() {
        try {
            // 启动server.js
            Process process = Runtime.getRuntime().exec("node server.js");
            // 读取server.js的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待server.js启动完成
            process.waitFor();
            // 打印启动完成信息
            System.out.println("server.js已启动");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
    private static void stopServer() {
        try {
            // 关闭server.js
            Process process = Runtime.getRuntime().exec("taskkill /F /IM node.exe");
            // 读取server.js的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 等待server.js关闭完成
            process.waitFor();
            // 打印关闭完成信息
            System.out.println("server.js已关闭");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
